package handin04;

import java.util.ArrayList;

/**
 * PrimeGenerator analysis integers 
 * 
 * @author Peter Tolstrup Aagesen, ptaa@itu.dk
 *
 */
public class PrimeGenerator 
{
	
	/**
	 * PrimeGenerator constructor
	 */
	public PrimeGenerator()
	{
		
	}
	
	/**
	 * Prints a list of the prime numbers from 1 to x to the console;
	 * @param x int
	 */
	public static void nextPrime(int x)
	{
		//Create a Integer ArrayList with primes
		ArrayList<Integer> primeList = getPrimeList(x);
		
		//Print the list
		printNumberListToConsole(primeList);
	}
	
	/**
	 * getPrimeList creates a list of the prime numbers from 1 to x
	 * @param x int
	 * @return Interger ArrayList with prime numbers 
	 */
	public static ArrayList<Integer> getPrimeList(int x)
	{
		//Create a new ArrayList with Integers
		ArrayList<Integer> primes = new ArrayList<Integer>();
		//Loop though all integers between 1 and x
		for(int i = 1; i <= x; i ++)
		{
			//Check if i is a prime
			if (isPrime(i))
			{
				//If i is a prime add it to the list
				primes.add(i);
			}
		}
		//Return list
		return primes;
	}
	
	/**
	 * getFirstFactor returns the lowest factor
	 * @param x int
	 * @return the lowest factor 
	 */
	public static int getFirstFactor(int x)
	{
		//Set return value to 1 (Any positive integer i divisible by 1)
		int firstFactor = 1;
		//Loop through all integer from 2 to x exclusive
		for(int i = 2; i < x; i ++)
		{
			//Check if x is divisible by i
			if(x % i == 0)
			{
				//If x is divisible by i, set return value to i and break loop
				firstFactor = i;
				break;
			}
		}
		//Return value
		return firstFactor;
	}
	
	/**
	 * isPrime test if x is a prime number
	 * @param x
	 * @return
	 */
	public static boolean isPrime(int x)
	{
		//Create return value and set it to true
		boolean isXPrime = true;
		//Loop through all integers from 2 to x exclusive (any positive integer is divisible by 1 and it self)
		for(int i = 2; i < x; i ++)
		{
			//If x is divisible by i
			if(x % i == 0)
			{
				//Set return value to false and break look
				isXPrime = false;
				break;
			}
		}
		//Return value
		return isXPrime;
	}
	
	/**
	 * printPrimesToConsole prints an ArrayList of numbers to the console
	 * @param primeList Integer ArrayList
	 */
	private static void printNumberListToConsole(ArrayList<Integer> primeList)
	{
		//Loop through all elements of the list (I couldn't the the enhanced for loop working)
		for(int i = 0; i < primeList.size(); i ++)
		{
			//Print element at i
			System.out.println(primeList.get(i));
		}
	}
}
